package com.funsolution.taskhey.dao.person;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.funsolution.taskhey.domain.Person;

@Stateless
public class PersonDaoImpl implements PersonDao {

    EntityManager entityManager;

    @Override
    public Person save(Person person) {
	entityManager.persist(person);

	return entityManager.find(Person.class, person.getId());
    }

    @Override
    public Person findByUsername(String username) {
	CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
	CriteriaQuery<Person> personCriteriaQuery = criteriaBuilder.createQuery(Person.class);
	Root<Person> personRoot = personCriteriaQuery.from(Person.class);
	personCriteriaQuery.where(criteriaBuilder.equal(personRoot.get("username"), username));
	Person person = null;
	try {
	    person = entityManager.createQuery(personCriteriaQuery).getSingleResult();
	} catch (NoResultException e) {

	}
	return person;
    }

    @PersistenceContext(name = "task_unit")
    public void setEntityManager(EntityManager entityManager) {
	this.entityManager = entityManager;
    }

    @Override
    public Person findByUsernameOrPassword(String username, String password) {
	CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
	CriteriaQuery<Person> personCriteriaQuery = criteriaBuilder.createQuery(Person.class);
	Root<Person> personRoot = personCriteriaQuery.from(Person.class);
	personCriteriaQuery.where(criteriaBuilder.and(
		criteriaBuilder.or(criteriaBuilder.equal(personRoot.get("username"), username), criteriaBuilder.equal(personRoot.get("email"), username)),
		criteriaBuilder.equal(personRoot.get("password"), password)));
	Person person = null;
	try {
	    person = entityManager.createQuery(personCriteriaQuery).getSingleResult();
	} catch (NoResultException e) {

	}
	return person;
    }

}
